﻿using System;
using System.Xml.Serialization;
using Kotonoha.Objects;

namespace Kotonoha.Server.Settings {
    public class Setting {

        public const string Common = "common";

        [XmlIgnore] internal DateTime lastModDate = DateTime.Now;
        [XmlIgnore] private TimeSpan lifetime = new TimeSpan(30 * 10000000); //default 30 seconds
        [XmlIgnore] internal string path;
        [XmlIgnore] internal bool clean = true;

        /// <summary>
        /// Lifetime in seconds
        /// </summary>
        [XmlIgnore]
        public long Lifetime {
            get { return lifetime.Ticks / 10000000; }
            set { lifetime = new TimeSpan(value*10000000); }
        }

        [XmlIgnore]
        internal DateTime LifeEnd {
            get {
                return lastModDate + lifetime;
            }
        }

        [XmlElement(ElementName = "data")]
        public SerializableDictionary<string, object> settings = new SerializableDictionary<string, object>();

        public object this[string s] {
            get {
                object o;
                settings.TryGetValue(s, out o);
                return o;
            }

            set {
                try {
                    SettingsManager.settingsMutex.WaitOne();
                    settings[s] = value;
                    lastModDate = DateTime.Now;
                    clean = false;
                } finally {
                    SettingsManager.settingsMutex.ReleaseMutex();
                }
            }
        }

        public int GetInt(string name, int def) {
            object o = this[name];
            return (int)(o ?? def);
        }
    }
}
